<template>
    <view class="page column">
        <hj-navbar :isCustomFun="true" :isShowBack="true" @handleBack="handleBack">
            <template #center>
                <view class="FZGongYeHei ft-42 t-3">调查问卷</view>
            </template>
        </hj-navbar>
        <view class="flex-auto w100 page-container column over-hide">
            <view class="bg big">
                <hj-image mode="aspectFill" src="home-bg.jpg" width="100%" height="100%" />
            </view>
            <view class="main flex-auto column over-auto-y">
                <view class="flex-auto column w100 content br-40">
                    <view class="count ft-50 bold mb-20 t-3"
                        ><text class="count-num pr-4">{{ currentIndex || 1 }}</text
                        >/<text class="pl-4">{{ total || 0 }}</text></view
                    >
                    <view>
                        <up-line-progress
                            :percentage="progress"
                            activeColor="#37b64a"
                            inactiveColor="#ededf7"
                            :showText="false"
                            height="18rpx"
                        ></up-line-progress>
                    </view>
                    <view class="flex-auto w100 mt-60 t-3">
                        <view v-for="(item, index) in list" :key="item.id">
                            <view v-if="currentIndex === index + 1">
                                <view class="ft-32 mb-30">{{ item.title }}</view>
                                <view class="ft-28">
                                    <view
                                        class="flex radio-item mt-20"
                                        :class="{ active: isSelected(item, radio) }"
                                        v-for="(radio, val) in item.option"
                                        :key="radio.id"
                                        @click="handleSelect(item, radio)"
                                    >
                                        <view class="radio-img" v-if="isSelected(item, radio)">
                                            <hj-image
                                                src="selected-01.svg"
                                                width="40rpx"
                                                height="40rpx"
                                            />
                                        </view>
                                        <view class="radio-left">{{ getLetter[val] || '' }}</view>
                                        <view>{{ radio.name }}</view>
                                    </view>
                                    <view
                                        class="flex mt-40 other-item"
                                        :class="isSelected(item, { id: otherId }) ? 'active' : ''"
                                        @click="handleSelect(item, { id: otherId, name: '其他' })"
                                    >
                                        <view>其他：</view>
                                        <view class="flex-auto input"
                                            ><up-input
                                                v-model="inputValue[currentIndex - 1]"
                                                placeholder="请输入"
                                                fontSize="28rpx"
                                                :clearable="true"
                                                :color="
                                                    isSelected(item, { id: otherId })
                                                        ? '#37b64a'
                                                        : '#333'
                                                "
                                                @change="handleInputChange"
                                            ></up-input
                                        ></view>
                                        <view
                                            class="radio-img"
                                            v-if="isSelected(item, { id: otherId })"
                                        >
                                            <hj-image
                                                src="selected-01.svg"
                                                width="40rpx"
                                                height="40rpx"
                                            />
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="center mb-30 mt-40">
                        <view class="but but-prev" v-if="currentIndex !== 1" @click="handlePrev"
                            >上一题</view
                        >
                        <view
                            class="but"
                            :class="[
                                currentIndex !== 1 ? 'ml-30' : '',
                                isFinish() ? '' : 'but-disabled'
                            ]"
                            v-if="currentIndex !== total"
                            @click="handleNext"
                            >下一题</view
                        >
                        <view
                            class="but ml-30"
                            :class="isFinish() ? '' : 'but-disabled'"
                            v-if="currentIndex === total"
                            @click="submit"
                            >提交</view
                        >
                    </view>
                </view>
                <!-- 安全底部 -->
                <hj-safe-footer />
            </view>
        </view>
    </view>
</template>

<script setup>
/**
 * @description 调查问卷主要内容区域组件。因为父组件需要使用page-container去监听一次用户的返回操作，防止用户触发此条件后导致页面空白。所以把内容提取为组件。让父组件渲染两次。
 * @author yinzhi
 * @date 2025-03-11
 */
import { onLoad } from '@dcloudio/uni-app'
import { logger } from '@/utils/log.js'
import { useStore } from 'vuex'
import { getQaListApi } from '@/libs/api/marketingApi.js'
import { ref, defineComponent, computed } from 'vue'
defineComponent({
    name: 'ContentArea'
})
const store = useStore()

// 写死的问卷数据，后续需要从后端获取后即可删除
import data from './data.json'
const dataJson = data.data

// 当前问题序号
const currentIndex = computed(() => store.state.questionnaire.currentIndex || 1)
// 问题总数
const total = ref(0)
// 当前进度
const progress = computed(() => (currentIndex.value / total.value) * 100)
// 列表
const list = ref([])
// 选中的问答答案信息列表
const selectedAnswers = computed(() => store.state.questionnaire.selectedAnswers || [])
// 根据角标得出字母
const getLetter = {
    0: 'A.',
    1: 'B.',
    2: 'C.',
    3: 'D.',
    4: 'E.',
    5: 'F.',
    6: 'G.'
}
// 自定义其他id
const otherId = ref('0')
// 输入框内容
const inputValue = ref([])

const emit = defineEmits()

onLoad(() => {
    getQuestionnaire()
})

// 获取调查问卷内容，初始化需要获取的数据
const getQuestionnaire = async () => {
    try {
        // const res = await getQaListApi()
        list.value = dataJson
        total.value = list.value.length
    } catch (error) {
        logger.error({ '[getQuestionnaire]-获取调查问卷内容失败：': error })
    }
}

/**
 * @description 提交问卷事件,提交成功后跳转到调查问卷结束页面
 */
const submit = async () => {
    try {
        if (!hasUnanswered()) {
            return
        }
        uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
        })
        let time = setTimeout(() => {
            uni.redirectTo({
                url: '/pages/marketing/questionnaire-end/index'
            })
            time && clearTimeout(time)
        }, 1000)
    } catch (error) {
        logger.error({ '[submit]-调查问卷提交失败：': error })
    }
}

// 上一题按钮事件
const handlePrev = () => {
    if (currentIndex.value > 1) {
        let index = currentIndex.value - 1
        store.commit('questionnaire/setCurrentIndex', index)
    }
}

// 下一题按钮事件
const handleNext = () => {
    if (!isFinish()) {
        return
    }
    if (currentIndex.value < total.value) {
        let index = currentIndex.value + 1
        store.commit('questionnaire/setCurrentIndex', index)
    }
}

/**
 * @description 单个问答是否完成选择判断 如果后续需要为选择也可进入下一题则可以移除该方法
 * 判断当前是否完成选择或者选择其他后是否输入内容
 */
const isFinish = () => {
    if (
        selectedAnswers.value.length !== currentIndex.value ||
        selectedAnswers.value[currentIndex.value - 1]?.options.length === 0
    ) {
        return false
    }
    const index = selectedAnswers.value[currentIndex.value - 1].options.findIndex(
        item => item.id === otherId.value
    )
    if (index !== -1 && !selectedAnswers.value[currentIndex.value - 1].options[index].name) {
        return false
    }
    return true
}

/**
 * @description 对所有问答进行检索是否有未选择的问答
 * 后续如果选择都按单个进行判断可使用isFinish方法移除当前方法
 */
const hasUnanswered = () => {
    const index = selectedAnswers.value.findIndex(item => !item.options.length)
    if (selectedAnswers.value.length !== total.value || index !== -1) {
        // 如果有未选择的问答，获取第一个未选择的问答的角标
        const firstUnansweredIndex = list.value.findIndex((_, idx) => {
            return !selectedAnswers.value.some(answer => answer.id === list.value[idx].id)
        })

        // 如果存在未选择的问答，更新当前索引并提示用户
        if (firstUnansweredIndex !== -1) {
            store.commit('questionnaire/setCurrentIndex', firstUnansweredIndex + 1)
        } else {
            store.commit('questionnaire/setCurrentIndex', index + 1)
        }
        return false
    }
    return true
}

// 输入框内容变化
const handleInputChange = e => {
    let text = e
    inputValue.value[currentIndex.value - 1] = text
    // 检查当前选中的值是否是"其他"
    const currentItem = list.value[currentIndex.value - 1]
    const selectedAnswerIndex = selectedAnswers.value.findIndex(
        answer => answer.id === currentItem.id
    )

    if (selectedAnswerIndex !== -1) {
        const existingAnswerIndex = selectedAnswers.value[selectedAnswerIndex].options.findIndex(
            option => option.id === otherId.value
        )
        if (existingAnswerIndex !== -1) {
            // 更新选项的 name 为输入框的值
            selectedAnswers.value[selectedAnswerIndex].options[existingAnswerIndex].name = text
            // 更新 Vuex 状态
            store.commit('questionnaire/setSelectedAnswers', selectedAnswers.value)
        }
    }
}

/**
 * @description 是否选中的状态 主要给元素上判断是否选中的样式
 * @param {Object} item 问题对象
 * @param {Object} radio 选项对象
 */
const isSelected = (item, radio) => {
    let selectedAnswerIndex = selectedAnswers.value.findIndex(answer => answer.id === item.id)
    if (selectedAnswerIndex !== -1) {
        let existingAnswerIndex = selectedAnswers.value[selectedAnswerIndex].options.findIndex(
            option => option.id === radio.id
        )
        if (existingAnswerIndex !== -1) {
            return true
        }
    }
    return false
}

/**
 * @description 点击回答选项
 * @param {Object} item 问题对象
 * @param {Object} radio 选项对象
 * @param {String} type 选项类型(单选/多选) radio/checkbox
 */
const handleSelect = (item, radio, type = 'radio') => {
    let selectedAnswerIndex = selectedAnswers.value.findIndex(answer => answer.id === item.id)
    let name = radio.id === otherId.value ? inputValue.value[currentIndex.value - 1] : radio.name

    // 检查 selectedAnswers 中是否存在该 item.id
    if (selectedAnswerIndex !== -1) {
        // 如果存在，检查 radio.id 是否已经存在
        let existingAnswerIndex = selectedAnswers.value[selectedAnswerIndex].options.findIndex(
            option => option.id === radio.id
        )

        if (type === 'radio') {
            // 单选逻辑：如果存在，删除选项；如果不存在，替换为新选项
            if (existingAnswerIndex !== -1) {
                // 如果存在，删除该选项
                selectedAnswers.value[selectedAnswerIndex].options.splice(existingAnswerIndex, 1)
            } else {
                // 清空其他选项并添加新选项
                selectedAnswers.value[selectedAnswerIndex].options = [{ id: radio.id, name: name }]
            }
        } else {
            // 多选逻辑：如果存在，删除选项；如果不存在，添加选项
            if (existingAnswerIndex !== -1) {
                // 如果存在，删除该选项
                selectedAnswers.value[selectedAnswerIndex].options.splice(existingAnswerIndex, 1)
            } else {
                // 如果不存在，添加选项
                selectedAnswers.value[selectedAnswerIndex].options.push({
                    id: radio.id,
                    name: name
                })
            }
        }
    } else {
        // 如果不存在，添加新的选项
        selectedAnswers.value.push({
            id: item.id,
            options: [{ id: radio.id, name: name }]
        })
    }
    // 更新 Vuex 状态
    store.commit('questionnaire/setSelectedAnswers', selectedAnswers.value)
}

// 返回事件
const handleBack = () => {
    emit('handleBack')
}
</script>

<style scoped lang="scss">
.other-item {
    position: relative;
    align-items: center;
    color: #333;
    .input {
        border-bottom: 1px solid #ddd;
        padding-right: 50rpx;
    }
}
.other-item.active {
    color: #37b64a;
    .input {
        border-bottom: 1px solid #37b64a;
    }
}
.radio-img {
    position: absolute;
    right: 10rpx;
    top: 50%;
    transform: translateY(-50%);
}
.radio-left {
    position: absolute;
    left: 24rpx;
    top: 50%;
    transform: translateY(-50%);
}
.radio-item {
    border: 1px solid #ddd;
    color: #333;
    min-height: 92rpx;
    border-radius: 12rpx;
    padding: 8rpx 50rpx 8rpx 60rpx;
    position: relative;
    align-items: center;
    line-height: 1.3;
}
.radio-item.active {
    color: #37b64a;
    border-color: #37b64a;
}
.count-num {
    color: #3edb20;
}
.but {
    display: flex;
    height: 82rpx;
    border-radius: 41rpx;
    align-items: center;
    justify-content: center;
    line-height: 1;
    width: 240rpx;
    font-size: 30rpx;
    border: 6rpx solid #37b64a;
    background: #43cd29;
    color: #fff;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 6px 0px;
}
.but-disabled {
    border: 6rpx solid rgba(55, 182, 74, 0.2);
    background: rgba(68, 205, 41, 0.6);
    box-shadow: none;
}
.but-prev {
    background: none;
    color: #43cd29;
}
.content {
    background: $uni-bg-color;
    padding: 40rpx;
    position: relative;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 6px 0px;
}
.page-container {
    position: relative;
}
.main {
    position: relative;
    z-index: 10;
    padding: 40rpx;
    .title {
        font-size: 68rpx;
    }
}
.bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    opacity: 0.6;
}
</style>
